package cn.edu.sgu.www.pms.service.impl;

import cn.edu.sgu.www.pms.dto.RoleMenuDTO;
import cn.edu.sgu.www.pms.entity.Menu;
import cn.edu.sgu.www.pms.entity.RoleMenu;
import cn.edu.sgu.www.pms.mapper.RoleMenuMapper;
import cn.edu.sgu.www.pms.pager.Pager;
import cn.edu.sgu.www.pms.pager.impl.RoleMenuPager;
import cn.edu.sgu.www.pms.service.RoleMenuService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author 沐雨橙风ιε
 * @version 1.0
 */
@Service
public class RoleMenuServiceImpl implements RoleMenuService {

    private final RoleMenuMapper roleMenuMapper;

    @Autowired
    public RoleMenuServiceImpl(RoleMenuMapper roleMenuMapper) {
        this.roleMenuMapper = roleMenuMapper;
    }

    @Override
    public void save(RoleMenuDTO roleMenuDTO) {
        List<String> menuIds = roleMenuDTO.getMenuIds();

        // 批量添加角色菜单
        RoleMenu roleMenu = new RoleMenu();

        roleMenu.setRoleId(roleMenuDTO.getRoleId());

        for (String menuId : menuIds) {
            roleMenu.setId(null);
            roleMenu.setMenuId(menuId);

            roleMenuMapper.insert(roleMenu);
        }
    }

    @Override
    public void cancel(RoleMenuDTO roleMenuDTO) {
        QueryWrapper<RoleMenu> queryWrapper = new QueryWrapper<>();

        queryWrapper.eq("role_id", roleMenuDTO.getRoleId());
        queryWrapper.in("menu_id", roleMenuDTO.getMenuIds());

        roleMenuMapper.delete(queryWrapper);
    }

    @Override
    public Page<Menu> selectByRoleId(RoleMenuPager pager) {
        Page<Menu> page = Pager.ofPage(pager);

        return roleMenuMapper.selectPageByRoleId(page, pager.getRoleId());
    }

    @Override
    public Page<Menu> selectUnselected(RoleMenuPager pager) {
        Page<Menu> page = Pager.ofPage(pager);

        return roleMenuMapper.selectPageUnselected(page, pager.getRoleId());
    }

}